#include<stdio.h>
#include<iostream>
#include<unistd.h>
#include<iostream>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
using namespace std;
#define NUM 1024
void Writer(int wfd)
{
    char buf[NUM]={0};
    int cnt = 0;
    while(true)
    {
        cout<<"子进程开始写: "<<endl;
        snprintf(buf,sizeof(buf),"I am father");
        // sprintf(buf,"%c",'a');
        // sleep(10);
        write(wfd,buf,strlen(buf));
        sleep(1);
        cnt++;
        if(cnt > 6)
            break;
    }
}
void Reader(int rfd)
{
    char buf[1024]={0};
    int num = 0;
    while(true)
    {
        int n =read(rfd,buf,sizeof(buf));
        cout<<"这是父进程: 读取结果: ";
        if(n > 0)
        {    
            cout<<buf<<endl;
            break;
        }
        else if(n == 0)
        {
            cout<<"child process exit father exit too"<<endl;
            break;
        }
    }
}
int main()
{
    int fd[2]={0};
    pipe(fd);
    int id = fork();
    if(id == 0)//子进程
    {
        close(fd[0]);
        Writer(fd[1]);
        close(fd[1]);//子进程写       
        exit(0);
    }
    close(fd[1]);
    Reader(fd[0]);//父进程读
    close(fd[0]);  
    int status = 0;
    waitpid(id,&status,0);
    cout<<"子进程收到的信号:"<<status<<endl;
    return 0;
}